{
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.6-final"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python38664bite0826404ec9f4f88a00ca1565c140931",
   "display_name": "Python 3.8.6 64-bit"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2,
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "40"
     },
     "metadata": {},
     "execution_count": 2
    }
   ],
   "source": [
    "'''\n",
    "lambda函数\n",
    "'''\n",
    "\n",
    "def make_incrementor(n):\n",
    "    return lambda x: x+n # 函数返回值是另一个函数，嵌套函数\n",
    "\n",
    "f = make_incrementor(40)\n",
    "f(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "[(4, 1), (3, 2), (2, 3), (1, 4)]"
     },
     "metadata": {},
     "execution_count": 6
    }
   ],
   "source": [
    "pairs = [(1,4),(2,3),(3,2),(4,1)]\n",
    "# pairs.sort()\n",
    "pairs.sort(key = lambda pair:pair[1]) # sort()的关键字参数key，指定列表中的第几个元素，这里指定第2个元素\n",
    "pairs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "[(4, 1), (3, 2), (2, 3), (1, 4)]"
     },
     "metadata": {},
     "execution_count": 10
    }
   ],
   "source": [
    "'''\n",
    "等效的写法\n",
    "'''\n",
    "def getsecond(lst):\n",
    "    return lst[1]\n",
    "\n",
    "pairs = [(1,4),(2,3),(3,2),(4,1)]\n",
    "pairs.sort(key = getsecond) # key 是函数名，是一个迭代器\n",
    "pairs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ]
}